from rest_framework import status
from rest_framework.decorators import api_view
from django.contrib.auth import authenticate
from django.contrib.auth import login as auth_login
from students.auth.backends import SchoolBackend
from rest_framework.response import Response
from .serializers import LoginSerializer
from django.http import HttpResponseRedirect
from django.urls import reverse

@api_view(['POST'])
def login(request):
    # username = request.POST['username']
    # password = request.POST['password']
    username = request.data['username']
    password = request.data['password']


    user = authenticate(username=username, password=password)
    resp = {'login': False, 'message': ''}
    if user is not None:
        auth_login(request, user, backend='students.auth.backends.SchoolBackend')
        resp['login'] = True
        # serializer = LoginSerializer(data=resp)
        # serializer.is_valid()
        # return Response(serializer.data, status=200)
        return HttpResponseRedirect(reverse("load_info"))
    else:
        serializer = LoginSerializer(data=resp)
        serializer.is_valid()
        return Response(serializer.data, status=400)

